package com.tmzn.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tmzn.config.SettingConfig;
import com.tmzn.domain.ImsMcMembers;
import com.tmzn.entity.param.LoginParam;
import com.tmzn.entity.param.RegisterParam;
import com.tmzn.jwt.JwtKit;
import com.tmzn.jwt.bean.IJwtAble;
import com.tmzn.jwt.bean.MyIJwtAble;
import com.tmzn.mapper.TDeviceRecordMapper;
import com.tmzn.redis.RedisCache;
import com.tmzn.transdata.RpcResult;
import com.tmzn.util.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    @Autowired
    private SettingConfig settingConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TDeviceRecordMapper tDeviceRecordMapper;
    @Autowired
    IImsMcMembersService iImsMcMembersService;
    public MyIJwtAble login(String userName, String password, String loginType) {
        return null;
    }


    /**
     * 获取用户登录后的信息
     * 1.设备列表
     *
     * @return
     */
    public RpcResult info() {
        MyIJwtAble user = JwtKit.getLoginUser();
        RpcResult rpcResult = RpcResult.ok();
        int id = user.getId();
        String tel = user.getTel();
        List<Map<String, Object>> maps = tDeviceRecordMapper.selectCommonSql("select * from ims_shopping_goods where weid = " + id);
        JSONObject obj = new JSONObject();
        obj.put("deviceList",maps);
        obj.put("info",user);
//        LambdaQueryWrapper<ImsMcMembers> userIc = new LambdaQueryWrapper();
//        userIc.eq(ImsMcMembers::getMobile,tel);
//        List<ImsMcMembers> list = iImsMcMembersService.list(userIc);
//        if(!list.isEmpty()){
//            obj.put("info",list.get(0));
//        }
        rpcResult.setData(obj);
        return rpcResult;
    }
    /**
     * 注册功能
     * @param loginParam
     * @return
     */
    public RpcResult login(LoginParam loginParam) {
        RpcResult rpcResult = new RpcResult();
        String mobile = loginParam.getMobile();
        String pwd = loginParam.getPwd();
        LambdaQueryWrapper<ImsMcMembers> userIc = new LambdaQueryWrapper();
        userIc.eq(ImsMcMembers::getMobile,mobile);
        userIc.eq(ImsMcMembers::getBelongsto,loginParam.getBelongs());
        List<ImsMcMembers> list = iImsMcMembersService.list(userIc);
        if(list.isEmpty()){
            rpcResult.setMsg("用户不存在或密码有误");
            return rpcResult;
        }else{
            MD5 md5 = MD5.create();
            String authkey = settingConfig.getAuthkey();
            ImsMcMembers imsMcMembers = list.get(0);
            String salt = imsMcMembers.getSalt();
            String newPWd = md5.digestHex(pwd + salt + authkey);
            if(!StrUtil.equals(newPWd,imsMcMembers.getPassword())){
                rpcResult.setMsg("用户不存在或密码有误");
                return rpcResult;
            }
            Long now = System.currentTimeMillis() / 1000;
            imsMcMembers.setLastLogin(now.intValue());
            iImsMcMembersService.updateById(imsMcMembers);
            String token = JwtKit.getToken(imsMcMembers);
            rpcResult.setData(token);
            rpcResult.setOk(true);
        }

        return rpcResult;
    }

    /**
     * 注册功能，需要在数据库创建一个模板用户 mobile为8888888888
     * @param registerParam
     */
    public RpcResult register(RegisterParam registerParam) {
        RpcResult rpcResult = new RpcResult();
        String msg = "";
        String verifyCode = registerParam.getVerifyCode();
        String mobile = registerParam.getMobile();
        String redisKey = mobile + "_register_code";
        String sendCode = redisCache.getCacheObject(redisKey);
        if(!StrUtil.equals(sendCode,verifyCode)){
            return RpcResult.fail("验证码有误");
        }
        String pwd = registerParam.getPwd();
        Integer belongs = registerParam.getBelongs();
        String salt = RandomUtil.randomString(8);
        String authkey = settingConfig.getAuthkey();
        LambdaQueryWrapper<ImsMcMembers> userIc = new LambdaQueryWrapper();
        userIc.eq(ImsMcMembers::getMobile,mobile);
        List<ImsMcMembers> list = iImsMcMembersService.list(userIc);
        if(!list.isEmpty()){
            msg = "用户已经存在";
            rpcResult.setMsg(msg);
            return rpcResult;
        }
        MD5 md5 = MD5.create();
        String newPWd = md5.digestHex(pwd + salt + authkey);
        LambdaQueryWrapper<ImsMcMembers> sampleUser = new LambdaQueryWrapper();
        sampleUser.eq(ImsMcMembers::getMobile,"18888888888");
        ImsMcMembers imsMcMembers = iImsMcMembersService.getOne(sampleUser);
        ImsMcMembers clone = ObjectUtil.clone(imsMcMembers);
        clone.setUid(null);
        clone.setSalt(salt);
        clone.setBelongsto(belongs);
        clone.setMobile(mobile);
        clone.setPassword(newPWd);
        iImsMcMembersService.save(clone);
        rpcResult.setOk(true);
        rpcResult.setMsg("注册成功");
        return rpcResult;
    }


    /**
     * 发送短信验证码
     * @param registerParam
     * @return
     */
    public RpcResult sendCode(RegisterParam registerParam) {
        String mobile = registerParam.getMobile();
        String redisKey = mobile + "_register_code";

        if(!canSendMsg(mobile)){
            return RpcResult.fail("短信发送过于频繁");
        }
        String pwd = registerParam.getPwd();
        String randomNumbers = RandomUtil.randomNumbers(6);
        log.info("发送验证码:{},{}",mobile,randomNumbers);
        SendSms.sendMsg(mobile,randomNumbers);
        redisCache.setCacheObject(redisKey,randomNumbers);
        redisCache.expire(redisKey,600);
        return RpcResult.ok();
    }

    private boolean canSendMsg(String mobile){
        String userCountKey = mobile+"_send_count";
        Integer count = redisCache.getCacheObject(userCountKey);
        boolean status = false;
        if(count == null){
            status =  true;
            count = 0;
        }
        if(count<=5){
            status = true;
        }
        count++;
        redisCache.setCacheObject(userCountKey,count);
        redisCache.expire(userCountKey,300);
       return status;
    }

    public RpcResult forgetPwd(RegisterParam registerParam) {
        String mobile = registerParam.getMobile();
        String verifyCode = registerParam.getVerifyCode();
        String redisKey = mobile + "_register_code";
        String sendCode = redisCache.getCacheObject(redisKey);
        if(!StrUtil.equals(sendCode,verifyCode)){
            return RpcResult.fail("验证码有误");
        }
        String pwd = registerParam.getPwd();
        LambdaQueryWrapper<ImsMcMembers> userIc = new LambdaQueryWrapper();
        userIc.eq(ImsMcMembers::getMobile,mobile);
        userIc.eq(ImsMcMembers::getBelongsto,registerParam.getBelongs());
        List<ImsMcMembers> list = iImsMcMembersService.list(userIc);
        if(list.isEmpty()) {
            return RpcResult.fail("找不到用户");
        }else{
            ImsMcMembers imsMcMembers = list.get(0);
            MD5 md5 = MD5.create();
            String authkey = settingConfig.getAuthkey();
            String newPWd = md5.digestHex(pwd + imsMcMembers.getSalt() + authkey);
            imsMcMembers.setPassword(newPWd);
            iImsMcMembersService.updateById(imsMcMembers);
            return RpcResult.ok();
        }
    }
}
